package com.aplink.generic.dialog;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

import android.util.SparseArray;

import com.aplink.generic.GenericFragment;
import com.aplink.generic.constant.type.ActionType;
import com.aplink.generic.constant.type.DialogStatus;

public class SparseDialog extends SparseArray<ApLinkAlertDialog> implements
        Serializable {

	private static final long serialVersionUID = -5525542506913994083L;

	public ApLinkAlertDialog get(final ActionType key) {
		return super.get(key.getCode());
	}

	public boolean has(final ActionType actionType,
	        final DialogStatus alertDialogStatusType) {
		if (this.get(actionType) != null) {
			if (this.get(actionType).has(alertDialogStatusType)) {
				return true;
			}
		}
		return false;
	}

	public void init(final GenericFragment genericFragment) {
		for (int i = 0; i < size(); i++) {
			valueAt(i).init(genericFragment);
		}
	}

	private void readObject(ObjectInputStream inputStream) throws IOException,
	        ClassNotFoundException {
		int size = inputStream.readInt();
		for (int i = 0; i < size; i++) {
			put(inputStream.readInt(),
			        (ApLinkAlertDialog) inputStream.readObject());
		}
	}

	public void show(final ActionType actionType,
	        final DialogStatus alertDialogStatusType) {
		if ((actionType == null) && (alertDialogStatusType != null)) {
			return;
		}
		if (has(actionType, alertDialogStatusType)) {
			this.get(actionType).getAlertDialog(alertDialogStatusType).show();
		}
	}

	public void show(final ActionType actionType,
	        final DialogStatus alertDialogStatusType, final String customMessage) {
		if ((actionType == null) && (alertDialogStatusType != null)) {
			return;
		}
		if (has(actionType, alertDialogStatusType)) {
			this.get(actionType)
			        .getAlertDialog(alertDialogStatusType, customMessage)
			        .show();
		}
	}

	private void writeObject(ObjectOutputStream outputStream)
	        throws IOException {
		outputStream.writeInt(size());
		for (int i = 0; i < size(); i++) {
			outputStream.writeInt(keyAt(i));
			outputStream.writeObject(valueAt(i));
		}
	}
}
